<template>
    <div style="width: 100%;">
        <div class="card">
            <NCard :title="($route.params.id ? '修改文章' : '写文章')">
                <NFlex vertical>
                    <n-input v-model:value="blogTitle" type="text" placeholder="标题" />
                    <n-input v-model:value="blogSummary" type="textarea" placeholder="摘要" :autosize="{
                        minRows: 1, maxRows: 3,
                    }" />
                    <NSelect v-model:value="selectedTags" :options="tagsOptions" remote :loading="tagsLoading" multiple
                        placeholder="选择标签"></NSelect>
                    <MdEditor v-model="blogText" :toolbars="toolbar" :footers="footers" :maxLength="maxInputLength">
                        <template #defFooters>
                            <span>
                                最大字数: {{ maxInputLength }}
                            </span>
                            <span>
                                <n-popover trigger="hover">
                                    <template #trigger>
                                        <span>
                                            <NIcon>
                                                <QuestionCircle16Regular />
                                            </NIcon>
                                        </span>
                                    </template>
                                    <span>本编辑器使用 md-editor-v3 项目.</span>
                                </n-popover>
                            </span>
                        </template>
                    </MdEditor>
                    <NButton type="success" style="width: fit-content;" @click="publishHandle">
                        {{ ($route.params.id ? '修改' : '发表') }}</NButton>
                </NFlex>
            </NCard>
            <!-- {{ postData }} -->
        </div>
    </div>
</template>

<script setup lang="ts">
import { NButton, NCard, NInput, NIcon, NPopover, NFlex, NSelect } from "naive-ui";
import { QuestionCircle16Regular } from '@vicons/fluent'
import { computed, ref, type Ref } from "vue";
import blogUtils from "@/api/blog";
import { useRoute, useRouter } from "vue-router";

import { MdEditor } from 'md-editor-v3';
import type { ToolbarNames, Footers } from "md-editor-v3"
import 'md-editor-v3/lib/style.css';


// 配置工具栏
const toolbar: ToolbarNames[] = [
    'bold', 'underline', 'italic',
    '-',
    'title', 'strikeThrough', 'sub', 'sup', 'quote', 'unorderedList', 'orderedList', 'task',
    '-',
    'codeRow', 'code', 'link', 'image', 'table', 'katex',
    '=',
    'revoke', 'next', 'save',
    '-',
    'preview', 'previewOnly', 'catalog',
];
// 配置编辑器页脚
const footers: Footers[] = ['markdownTotal', 0, '=', 1, 'scrollSwitch'];
// 最大输入长度限制
const maxInputLength = 10000;
const tagsLoading = ref(true)


// 默认编辑内容
const blogText = ref(`> 支持markdown语法, $\\LaTeX$ 公式等。\n\n### 标题\n\n- 无序\n- 列表\n\n1. 有序\n1. 列表\n\n\`\`\`cpp\nint main(){}\n\`\`\` `);
const blogTitle = ref("")
const blogSummary = ref("")
const blogCategory = ref("测试")
const tagsOptions: Ref<[{ label: string, value: string }] | never[]> = ref([])
const tagsOptionsDictionary = computed(() => {
    return tagsOptions.value.reduce((acc, item) => {
        acc[item.value] = item.label;
        acc
        return acc;
    }, {} as {
        [key: string]: string;
    });
})
const selectedTags = ref([])
const blogTags = computed(() => {
    return selectedTags.value.map((value: string) => {
        return {
            label: tagsOptionsDictionary.value[value],
            value
        }
    })
})

blogUtils.getTags().then(
    (res) => {
        tagsOptions.value.push(...res)
        tagsLoading.value = false;
    }
).catch((err) => {
    console.log(err);
}
)

const route = useRoute();
if (route.params.id) {
    blogUtils.view(route.params.id as string).then(
        (data: any) => {
            console.log(data);
            blogText.value = data.body.content;
            blogTitle.value = data.title;
            blogSummary.value = data.summary;
            selectedTags.value.length = 0;
            selectedTags.value = data.tags.map((i: { value: string }) => {
                return i.value;
            });

        }
    ).catch((err) => {
        console.log(err);
    });
}

console.log(route.params);

const postData = computed(() => {
    return {
        id: route.params.id,
        title: blogTitle.value,
        summary: blogSummary.value,
        body: {
            content: blogText.value,
            contentHtml: ''
        },
        category: {
            id: "1",
            avatar: '',
            categoryName: '',
            description: ''
        },
        tags: blogTags.value
    }
})

const router = useRouter();
function publishHandle() {
    window.$utils.message.info("正在提交");
    blogUtils.publish(postData.value).then(
        (id: string) => {
            console.log(id);
            router.push({ name: "blogview", params: { id } })
        }
    ).catch((err) => {
        console.log(err);
    });
}
</script>


<style scoped>
@media (max-width: 599px) {
    .card {
        width: calc(599px - 200px);
        max-width: 100%;
        margin: auto;
    }
}

/* 当视口宽度大于或等于600px时 */
@media (min-width: 600px) {
    .card {
        width: calc(100% - 200px);
        margin-left: 100px;
        margin-right: 100px;
    }
}

.card {
    margin-top: 1rem;
}
</style>